import fs from 'fs-extra';
import fg from 'fast-glob';
import ini from 'ini';
import path from 'path';
import { env } from 'process';

interface ProjectCfg {
    Project: {
        code: string,
        Name: string, 
        Alias?: string,
        ProjectType?: 'H5ts' | 'Unity' | 'Laya',
        chatid?: string
    }, 
    Svn: {
        ClientSvn: string, 
        DesignerSvn: string, 
        SvrSvn: string
    },
    Build?: {
        ProjRoot: string
    }
}

export class ProjIniCfgParser {

    private static ins: ProjIniCfgParser;
    public static get Instance(): ProjIniCfgParser {
        if(!ProjIniCfgParser.ins) ProjIniCfgParser.ins = new ProjIniCfgParser();
        return ProjIniCfgParser.ins;
    }

    /**
     * 通过项目中文名获取其ini配置。
     * @param projectName 
     * @returns 
     */
    async getProjIniCfgByChatCode(chatCode: string): Promise<ProjectCfg | null> {
        if (!env.CFG_LOCAL) return null;
        const inis = fg.sync(['*.ini', '*.json'], { cwd: env.CFG_LOCAL, ignore: ['all.svn.json']});
        for (const i of inis) {
            const icontent = await fs.readFile(path.join(env.CFG_LOCAL, i), 'utf-8');
            const iext = path.extname(i);
            let iCfg: ProjectCfg;
            if (iext == '.json') {
                iCfg = JSON.parse(icontent);
            } else {
                iCfg = ini.parse(icontent) as ProjectCfg;
            }
            if (iCfg.Project.chatid == chatCode) {
                iCfg.Project.code = path.basename(i, iext);
                return iCfg;
            }
        }
        return null;
    }
}
